<template>
  <van-swipe
    :loop="loop"
    :vertical="vertical"
    :autoplay="autoplay"
    :indicator-color="indicatorColor"
    :show-indicators="show_indicators"
    lazy-render
    @change="handleChange"
    ref="swiperRef"
  >
    <slot></slot>
  </van-swipe>
</template>

<script>
import {
  computed,
  onMounted,
  ref,
  watch,
  watchEffect,
} from "@vue/runtime-core";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
export default {
  name: "Swiper",
  props: {
    //轮播时隔
    autoplay: {
      style: String,
      default: "5000",
    },
    //轮播方向
    vertical: {
      style: Boolean,
      default: false,
    },
    //按钮active的颜色
    indicatorColor: {
      style: String,
      default: "#ffd01e",
    },
    //是否显示按钮
    show_indicators: {
      style: Boolean,
      default: false,
    },
    loop: {
      style: Boolean,
      default: true,
    },
  },
  setup() {
    // swiper实例
    const swiperRef = ref(null);
    const store = useStore();
    //
    onMounted(() => {
      swiperRef.value.swipeTo(store.state.topic.status.topicIndex - 1);
    });
    // 翻页状态监听
    watchEffect(() => {
      if (store.state.topic.status.next) {
        // 下一页
        swiperRef.value.next();
        store.commit("topic/handleTopicStatus", { type: "next" });
      } else if (store.state.topic.status.prev) {
        // 上一页
        swiperRef.value.prev();
        store.commit("topic/handleTopicStatus", { type: "prev" });
      }
    });
    // 跳转到当前题页
    const current = computed(() => {
      return store.state.topic.current;
    });
    watch(current, () => {
      swiperRef.value.swipeTo(store.state.topic.status.topicIndex - 1);
    });
    // 翻页监听
    const route = useRoute();
    const routePath = route.path.split("/")[1];
    const handleChange = (index) => {
      if (routePath === "answerPage") {
        store.commit("topic/handleTopicStatus", {
          type: "topicIndex",
          value: index + 1,
        });
      }
    };

    return { handleChange, swiperRef };
  },
};
</script>

<style scoped lang="less">
.van-swipe {
  width: 100%;
  height: 100%;
}
:deep(.van-swipe__indicator) {
  background-color: #fff;
}
</style>
